<template>
  <data-summary :amountCount="amountCount" @onChangeCommission="onChangeCommission" />
  <a-divider :margin="16" />
  <!-- 筛选 -->
  <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="onSearch" @popup-visible-change="popupVisibleChange" />
  <div class="flex items-center justify-between mb-5">
    <a-link @click="funsAndNounVisible = true">
      <template #icon>
        <icon-file />
      </template>
      功能及名词解释
    </a-link>
    <div class="flex items-center justify-between">
      <div class="mr-4" v-permission="'svms:order:short-order.settlementView'">
        <a-button @click="settlementViewFn">查看结算明细</a-button>
      </div>
      <div class="mr-4" v-permission="'svms:order:short-order.batchRevokeConfirmFee'">
        <a-button @click="batchRevokeConfirmFeeFn">批量撤销结算</a-button>
      </div>
      <div class="mr-4" v-permission="'svms:order:short-order.addfee'">
        <a-button @click="addfeeFn">添加用户缴费</a-button>
      </div>
      <div v-permission="'svms:order:short-order.confirmfee'">
        <a-button type="primary" @click="batchExpensesFn">批量结算</a-button>
      </div>
    </div>
  </div>
  <!-- 表格 -->
  <table-index
    class="insure-card-table"
    :selectedKeys="expensesKeys"
    :table="tableCompulsory"
    @selection-change="selectionChange"
    @loadData="loadCompulsoryData"
  >
    <template #table-summary v-if="tableNotice.dataList.length > 0">
      <a-alert class="custom-alert">
        <p class="truncate">
          {{ tableNotice.dataList[0].operateLog }}
        </p>
        <template #action>
          <a-link @click="showMoreNoticeModal = true">更多</a-link>
        </template>
      </a-alert>
    </template>
    <template #amount="{ record }">
      <div v-if="record.totalEdit">
        <div class="flex items-center justify-center">
          <a-input-number
            v-model="record.amount"
            @change="(value) => onChangeTotalAmount(value, record)"
            hide-button
            class="mr-1"
            placeholder="请输入"
            :error="record.totalAmountError"
            :precision="2"
            :min="0.01"
            :max="99999999.99"
          />
          <icon-check-circle-fill size="32" class="cursor-pointer color-1890ff" @click="onClickTotalAmount(record)" />
          <icon-close-circle-fill size="32" class="cursor-pointer" @click="onCloseTotalAmount(record)" />
        </div>
        <div class="arco-form-item-message" v-if="record.totalAmountError">{{ totalAmountError }}</div>
      </div>
      <div v-else>
        {{ record.amount }}
        <icon-edit v-if="record.canModify" class="cursor-pointer" @click="editTotalAmount(record)" />
      </div>
    </template>
    <template #payAmount="{ record }">
      <div v-if="record.payAmountEdit">
        <div class="flex items-center justify-center">
          <a-input-number
            v-model="record.payAmount"
            @change="(value) => onChangePayAmount(value, record)"
            hide-button
            class="mr-1"
            placeholder="请输入"
            :error="record.payAmountError"
            :precision="2"
            :min="0"
            :max="99999999.99"
          />
          <icon-check-circle-fill size="32" class="cursor-pointer color-1890ff" @click="onClickPayAmount(record)" />
          <icon-close-circle-fill class="cursor-pointer" size="32" @click="onClosePayAmount(record)" />
        </div>
        <div class="arco-form-item-message" v-if="record.payAmountError">{{ payAmountError }}</div>
      </div>
      <div v-else>
        {{ record.payAmount }}
        <!-- <icon-edit v-if="isAmountEdit(record)" class="cursor-pointer" @click="record.payAmountEdit = true" /> -->
      </div>
    </template>
    <template #payTypeNameList="{ record }">
      <div v-for="(item, index) in record.payTypeNameList" :key="index">
        {{ item }}
      </div>
    </template>
    <template #remark="{ record }">
      <div class="all-remark">
        {{ record.remark }}
      </div>
      <a-link v-if="record.remark" @click="onShowMoreRemark(record)">查看更多</a-link>
    </template>
  </table-index>

  <!-- 编辑费用 -->
  <edit-fee-modal ref="editFeeModalRef" @ok="feepageConfirm" />
  <orderfee ref="orderfeepage" @feepageConfirm="feepageConfirm" />
  <!-- 违章编辑费用 -->
  <violationEditFeeModal ref="violationEditFee" @feepageConfirm="feepageConfirm" />
  <!-- 修改对账金额 -->
  <checkAccountModal ref="checkAccountRef" @feepageConfirm="feepageConfirm" />
  <qcode-modal
    v-model:visible="payQCodeModal"
    :details="clickRecord"
    @close="payQCodeClose"
    :qcodeTitle="qcodeTitle"
    :qcodeCfLoading="qcodeCfLoading"
    @confirm="qcodeConfirm"
    :from="qrcodeFrom"
  />
  <!-- 修改抽佣比例 -->
  <change-commission-modal v-model:visible="changeCommissionModalVisible" />

  <!-- 查看更多备注 -->
  <a-modal
    width="45vw"
    v-model:visible="showMoreRemarkModal"
    title="费用备注"
    ok-text="关闭"
    hide-cancel
    @before-open="beforeOpenRemark"
    @ok="showMoreRemarkModal = false"
  >
    <table-index :table="tableRemark" />
  </a-modal>

  <!-- 查看更多通知 -->
  <a-modal width="45vw" v-model:visible="showMoreNoticeModal" title="更多通知" ok-text="关闭" hide-cancel @ok="showMoreNoticeModal = false">
    <table-index :table="tableNotice" />
  </a-modal>
  <!-- 功能及名词解释 -->
  <functionsAndNoun v-model:visible="funsAndNounVisible" />
  <!-- 添加备注弹框 -->
  <add-remark-modal ref="addRemarkRef" mode="shortOrderCost" title="添加费用备注" @ok="loadCompulsoryData" />
  <!-- 结算弹窗 -->
  <settlementModal ref="settlementModalRef" @feepageConfirm="feepageConfirm" />
  <!-- 添加用户缴费 -->
  <addFeeModal ref="addFeeModalRef" @ok="addFeeOkFn" />
  <!-- 查看结算明细 -->
  <view-settlement-modal v-model="viewSettlementModalVisible" :data="viewSettlementModalData" @ok="loadCompulsoryData" />
</template>

<script setup name="ShortOrderCost" lang="ts">
  import DataSummary from './data-summary.vue'
  import qcodeModal from '@/views/confirmFee/modals/qcode-modal.vue'
  import orderfee from '@/views/confirmFee/order/index.vue'
  import violationEditFeeModal from '@/views/editFee/violation/index.vue'
  import editFeeModal from '../../components/edit-fee-modal.vue'
  import checkAccountModal from './check-account-modal.vue'
  import changeCommissionModal from './change-commission-modal.vue'
  import functionsAndNoun from '../../../components/functionsAndNoun.vue'
  import addRemarkModal from '../../components/list-modals/add-remark-modal.vue'
  import settlementModal from '@/views/confirmFee/order/settlement-modal.vue'
  import addFeeModal from '../../components/list-modals/add-fee-modal.vue'
  import ViewSettlementModal from '@/views/finance/examine/shortOrder/modal/view-settlement-modal.vue'

  import { Modal } from '@arco-design/web-vue'
  import { useTable } from '@/hooks/table'
  import {
    getShortOrdrFeeDetail,
    checkManyToConfirm,
    feeAmountCount,
    remarkLogList,
    modifyOrderFee,
    orderFeeDel,
    selectFeeItemName,
    orderNoticeListAPI,
    getShortOrdrDetails,
  } from '@/api/order/sOrder'
  import { rejectShortOrderBill } from '@/api/finance/examine'
  import { ref, onMounted, computed, reactive, h } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { usePageDict } from '@/hooks/useDict'
  import { cancelPay } from '@/api/common'
  import { Notification } from '@arco-design/web-vue'
  import { cloneDeep } from 'lodash-es'

  const qrcodeFrom = ref('')
  const qcodeCfLoading = ref(false)
  const qcodeTitle = ref('收款码')
  const payQCodeModal = ref(false)
  const dict = usePageDict('costConfirmDict')
  const orderDict = usePageDict('shortOrderDict')
  const editFeeModalRef = ref()
  const violationEditFee = ref()
  const checkAccountRef = ref()
  const orderfeepage = ref()
  const feeDetail = ref<any>({})
  const expensesKeys = ref<number[]>([]) //合并id
  const queryParam = reactive<any>({})
  const clickRecord = ref<any>({})
  const changeCommissionModalVisible = ref(false)
  const showMoreRemarkModal = ref(false)
  const showMoreNoticeModal = ref(false)
  const cloneTableCompulsory = ref<any[]>([])
  const totalAmountError = ref('')
  const payAmountError = ref('')

  const props = defineProps({
    orderId: Number,
  })
  // 修改总额
  // 650需求：支付方式为押金抵扣时弹出提示
  const editTotalAmount = (record: any) => {
    if (record.payTypeList.includes(4)) {
      Modal.confirm({
        title: '提示',
        content: '该金额已通过押金抵扣支付成功，是否确认修改',
        onOk: () => {
          record.totalEdit = true
        },
        onCancel: () => {
          record.totalEdit = false
        },
      })
    } else {
      record.totalEdit = true
    }
  }

  // 获取筛选费用名称
  const selectFeeName = ref([])
  const selectFeeNameLoading = ref(false)
  const getFeeItemName = () => {
    selectFeeNameLoading.value = true
    selectFeeItemName({ id: props.orderId })
      .then((res: any) => {
        selectFeeName.value = res.result.map((item: any) => {
          return {
            label: item,
            value: item,
          }
        })
      })
      .finally(() => {
        selectFeeNameLoading.value = false
      })
  }

  // 查询条件
  const searchList = computed(() => {
    return [
      {
        label: '费用名称',
        prop: 'itemNameList',
        type: 'a-select',
        options: selectFeeName.value,
        multiple: true,
        loading: selectFeeNameLoading.value,
      },
      { label: '费用类型', prop: 'feeType', type: 'a-select', options: dict.orderFeeTypeEnum },
      { label: '收支类型', prop: 'costType', type: 'a-select', options: dict.costTypeEnum },
      { label: '结算状态', prop: 'feeStatuses', type: 'a-select', options: dict.orderFeeStatusEnum, multiple: true },
      { label: '生成节点', prop: 'createNodeList', type: 'a-select', options: orderDict.feeCreateNodeEnum, multiple: true },
    ]
  })

  const onSearch = () => {
    loadCompulsoryData()
    expensesKeys.value = []
  }

  const popupVisibleChange = (item: any, visible: boolean) => {
    if (item.prop == 'itemNameList' && visible) {
      getFeeItemName()
    }
  }

  const tableRemark = useTable({
    pagination: false,
    columns: [
      { title: '创建时间', dataIndex: 'createTime' },
      { title: '操作人', dataIndex: 'createUserName' },
      { title: '备注信息', dataIndex: 'operateLog' },
    ],
  })

  const tableNotice = useTable({
    pagination: false,
    columns: [
      { title: '通知时间', dataIndex: 'createTime', width: 180 },
      { title: '通知内容', dataIndex: 'operateLog' },
    ],
  })

  // 获取订单详情
  const shortOrderDetails = ref<any>({})
  const getShortOrderDetail = () => {
    return new Promise((resolve) => {
      getShortOrdrDetails({ id: props.orderId }).then((res: any) => {
        resolve(res.result)
      })
    })
  }

  const isAmountEdit = (record: any) => {
    // feeType 1 线下费用 2 线上费用
    // orderStatus 10 待排车 100 待用车 200 用车中 300 已还车 1000 已完成 -100 已取消
    // feeStatus 0 未结算 1 结算中 3 部分结算 2 已结算 9 无需结算
    // billStatus 1 待对账 2 部分对账 3 已对账 9 关闭对账

    // 线下费用
    if (record.feeType == 1) {
      return record.feeStatus == 0 || record.feeStatus == 3
    }

    // 线上费用
    if (record.feeType == 2) {
      return (
        (shortOrderDetails.value.orderStatus == '1000' || shortOrderDetails.value.orderStatus == '-100') &&
        (record.feeStatus == 0 || record.feeStatus == 3) &&
        record.billStatus == 1 &&
        record.billedAmount == 0
      )
    }

    return false
  }

  const currentRemark = ref<any>({})
  const beforeOpenRemark = () => {
    tableRemark.tableLoading = true
    remarkLogList({ orderId: currentRemark.value.orderId, id: currentRemark.value.id })
      .then((res: any) => {
        tableRemark.dataList = res.result
      })
      .finally(() => {
        tableRemark.tableLoading = false
      })
  }

  const onShowMoreRemark = (record: any) => {
    console.log('onShowMoreRemark', record)
    currentRemark.value = record
    showMoreRemarkModal.value = true
  }

  const onChangeTotalAmount = (value: any, record: any) => {
    console.log('onChangeTotalAmount', value, record)
    // payTypeList -1 嘉联聚合支付
    if ([-1].includes(record.payTypeList) && (value == undefined || value < record.amount)) {
      record.totalAmountError = true
      totalAmountError.value = '总额需>=聚合支付金额，请重新输入'
    } else if (value == undefined || value < record.amountLimit.min) {
      record.totalAmountError = true
      totalAmountError.value = '总额需>=实结金额，请重新输入'
    } else {
      record.totalAmountError = false
      totalAmountError.value = ''
    }
  }

  const onChangePayAmount = (value: any, record: any) => {
    console.log('onChangePayAmount', value, record)
    // payTypeList -1 嘉联聚合支付
    if ([-1].includes(record.payTypeList) && (value == undefined || value < record.amount)) {
      record.payAmountError = true
      payAmountError.value = '实结金额需>=聚合支付金额，请重新输入'
    } else if (value == undefined || value > record.amount) {
      record.payAmountError = true
      payAmountError.value = '实结金额需<=总额，请重新输入'
    } else {
      record.payAmountError = false
      payAmountError.value = ''
    }
  }

  const onCloseTotalAmount = (record: any) => {
    const current = cloneTableCompulsory.value.find((item: any) => item.id == record.id)
    record.amount = current.amount
    record.totalEdit = false
    record.totalAmountError = false
  }

  const onClickTotalAmount = (record: any) => {
    if (record.totalAmountError) {
      return
    }

    modifyOrderFee({ id: record.id, amount: record.amount })
      .then(() => {
        record.totalEdit = false
        record.totalAmountError = false
        totalAmountError.value = ''
        Message.success('修改成功')
        loadCompulsoryData()
        getFeeAmount()
      })
      .catch((error: any) => {
        console.log('error', error)
        // Message.error(error.message)
      })
  }

  const onClosePayAmount = (record: any) => {
    const current = cloneTableCompulsory.value.find((item: any) => item.id == record.id)
    record.payAmount = current.payAmount
    record.payAmountEdit = false
    record.payAmountError = false
  }

  const onClickPayAmount = (record: any) => {
    if (record.payAmountError) {
      return
    }

    modifyOrderFee({ id: record.id, amount: record.amount, payAmount: record.payAmount })
      .then(() => {
        record.payAmountEdit = false
        record.payAmountError = false
        payAmountError.value = ''
        Message.success('修改成功')
        loadCompulsoryData()
        getFeeAmount()
      })
      .catch((error: any) => {
        console.log('error', error)
        // Message.error(error.message)
      })
  }

  const onChangeCommission = () => {
    changeCommissionModalVisible.value = true
  }

  // 配置金额限制
  const getAmountLimit = (record: any) => {
    const limit = {
      min: 0.01,
      max: 99999999.99,
    }
    // 当前生效的结算单数量
    const settlementCount = record.settlementCount
    // 当前已对账金额
    const billedAmount = record.billedAmount
    // 实结金额
    const payAmount = record.payAmount
    // 当前生效的结算单数量 = 0，说明没有结算和对账，无限制
    // 当前生效的结算单数量 > 1，最小是实结金额，最大不限制
    // 当前生效的结算单数量 = 1，如果 billedAmount > 0，最小是实结金额，billedAmount == 0 的话，无限制
    if (settlementCount > 1) {
      limit.min = payAmount
    }
    if (settlementCount == 1) {
      if (billedAmount > 0) {
        limit.min = payAmount
      }
    }
    return limit
  }
  const getShortOrdrList = () => {
    return new Promise((resolve) => {
      getShortOrdrFeeDetail({ orderId: props.orderId, ...queryParam }).then((res: any) => {
        feeDetail.value = res.result
        const result = res.result
        tableCompulsory.dataList = result.map((item: any) => {
          const limit = getAmountLimit(item)
          return {
            ...item,
            totalEdit: false,
            payAmountEdit: false,
            totalAmountError: false,
            payAmountError: false,
            amountLimit: limit,
          }
        })
        resolve(tableCompulsory.dataList)
      })
    })
  }

  const getOrderNotice = () => {
    tableNotice.tableLoading = true
    orderNoticeListAPI({ id: props.orderId })
      .then((res: any) => {
        tableNotice.dataList = res.result
      })
      .finally(() => {
        tableNotice.tableLoading = false
      })
  }

  const loadCompulsoryData = () => {
    tableCompulsory.tableLoading = true

    getShortOrdrList()
      .then((data: any) => {
        // 已结算 无需结算 不支持选择
        data.map((it: any) => {
          // 条件1：显示结算按钮
          const condition1 =
            (it.feeType == 1 || (it.feeType == 2 && [1000, -100].includes(shortOrderDetails.value.orderStatus))) &&
            [0, 3].includes(it.feeStatus)
          // 条件2：显示撤销结算按钮
          const condition2 = it.payAmount !== 0 && it.waitBillAmount !== 0 && it.billStatus != 9
          // 禁用条件 既不显示结算也不显示撤销结算的禁用掉
          it.disabled = !condition1 && !condition2
        })
        cloneTableCompulsory.value = cloneDeep(data)
      })
      .finally(() => {
        tableCompulsory.tableLoading = false
      })
  }
  // 添加备注
  const addRemarkRef = ref()
  // 结算弹窗
  const settlementModalRef = ref()
  // 添加用户缴费
  const addFeeModalRef = ref()

  // table 配置
  const tableCompulsory = useTable({
    pagination: false,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    columns: [
      { title: '费用名称', dataIndex: 'itemName', width: 150, fixed: 'left' },
      {
        title: '总额(元)',
        dataIndex: 'amount',
        slotName: 'amount',
        width: 150,
        titleTooltipContent:
          '当费用状态为部分结算/已结算，对账状态为未对账，且只结算过一次，允许修改总额，结算多次则先驳回结算，再修改总额',
      },
      { title: '实结(元)', dataIndex: 'payAmount', slotName: 'payAmount', width: 100 },
      { title: '未结(元)', dataIndex: 'waitPayAmount', width: 100 },
      { title: '生成节点', dataIndex: 'createNodeName', width: 90 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 100 },
      { title: '结算状态', dataIndex: 'feeStatusName', width: 90 },
      { title: '支付方式', dataIndex: 'payTypeNameList', slotName: 'payTypeNameList', width: 100 },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 100 },
      { title: '操作人', dataIndex: 'updateUserName', width: 100 },
      { title: '操作时间', dataIndex: 'updateTime', width: 180 },
      { title: '结算人', dataIndex: 'settlementUserName', width: 100 },
      { title: '结算时间', dataIndex: 'settlementTime', width: 180 },
      { title: '费用备注', dataIndex: 'remark', slotName: 'remark', width: 220 },
    ],
    operates: [
      // 短租按钮
      {
        // 结算
        label: '结算',
        permission: 'svms:order:short-order.confirmfee',
        show: (record: any) => {
          return (
            (record.feeType == 1 || (record.feeType == 2 && [1000, -100].includes(shortOrderDetails.value.orderStatus))) &&
            [0, 3].includes(record.feeStatus)
          )
        },
        method: (record: any) => {
          settlementModalRef.value.show(JSON.stringify([record.id]), record)
        },
      },
      {
        // 实结=0不展示该按钮
        // 未对账=0时，不展示该按钮
        // 无需对账时不展示该按钮(关闭对账)
        label: '撤销结算',
        permission: 'svms:order:short-order.revokeConfirmFee',
        show: (record: any) => record.payAmount !== 0 && record.waitBillAmount !== 0 && record.billStatus != 9,
        method: (record: any) => {
          Modal.confirm({
            title: '撤销结算',
            content: () =>
              h('div', {}, [
                h('p', {}, `未对账总额：${record.waitBillAmount || 0}元，确认撤销结算吗？`),
                h('p', { style: 'color: red' }, '注：'),
                h('p', { style: 'color: red' }, '1.未对账的金额支持撤销结算，撤销后需重新结算'),
                h('p', { style: 'color: red' }, '2.支付方式为聚合支付的金额不支持撤销结算'),
                h('p', { style: 'color: red' }, '3.支付方式为押金抵扣且使用芝麻免押的不支持撤销结算'),
              ]),
            onOk: () => {
              rejectShortOrderBill({ idList: [record.id], operateType: 1 }).then((res: any) => {
                Message.success(res.message)
                loadCompulsoryData()
              })
            },
          })
        },
      },
      {
        label: '收款码',
        permission: 'svms:order:short-order.qrcode',
        show: (record: any) => record.feeStatus == 1 && record.confirmPayType != 4,
        method: (record: any) => {
          console.log('收款码', record)

          qrcodeFrom.value = 'shortOrderQRCode'
          qcodeTitle.value = '收款码'
          clickRecord.value = {
            ...record,
            bizType: 1,
            refId: record.orderId,
          }
          payQCodeModal.value = true
        },
      },
      {
        // 取消收款
        label: '取消收款',
        permission: 'svms:order:short-order.qrcodeCancel',
        // 1 取消收款，原则上是给嘉联支付做的，结算中可以取消掉，操作也是弹嘉联支付的弹窗
        // 2 结算方式选择押金抵扣，等待支付宝回调过程中也会是 结算中，此时不应显示取消收款（confirmPayType != 4）
        show: (record: any) => record.feeStatus == 1 && record.confirmPayType != 4,
        method: (record: any) => {
          console.log('取消收款', record)

          qrcodeFrom.value = 'shortOrderQRCodeCancel'
          qcodeTitle.value = '取消收款'
          clickRecord.value = {
            ...record,
            bizType: 1,
            refId: record.orderId,
          }
          payQCodeModal.value = true
        },
      },
      {
        // 添加备注
        label: '添加费用备注',
        permission: 'svms:order:short-order.addremark',
        show: (record: any) => record.feeStatus != 90,
        method: (record: any) => {
          addRemarkRef.value.show(record)
        },
      },
      {
        /**
         * 1. 线下费用：待结算、无需结算的支持删除
         * 2. 线上费用且订单为自动维护：已完成/已取消前，都不支持删除（无论系统同步or自己添加）
         * 3. 线上费用且订单为手动维护：未结算、无需结算的支持删除（无论系统同步or自己添加）
         */
        // feeType 1 线下费用 2 线上费用
        // orderStatus 10 待排车 100 待用车 200 用车中 300 已还车 1000 已完成 -100 已取消
        // feeStatus 0 待结算 1 结算中 3 部分结算 2 已结算 9 无需结算
        // channelOrderMaintenance 1 自动维护 2 手动维护
        label: '删除',
        permission: 'svms:order:short-order.delete',
        show: (record: any) => {
          // 条件1：费用状态为待结算或无需结算
          if ([0, 9].includes(record.feeStatus)) {
            // 条件2：费用类型为线下费用或线上费用的手动维护
            if (record.feeType == 1 || (record.feeType == 2 && shortOrderDetails.value.channelOrderMaintenance == 2)) {
              return true
            }
            // 条件3：费用类型为线上费用的自动维护，订单状态为已完成或已取消
            if (record.feeType == 2 && shortOrderDetails.value.channelOrderMaintenance == 1) {
              return [1000, -100].includes(shortOrderDetails.value.orderStatus)
            }
          }
          return false
        },
        method: (record: any) => {
          Modal.confirm({
            title: '删除',
            bodyStyle: {
              'text-align': 'center',
            },
            content: '费项可能存在已结算或已对账金额，确认要删除费用吗？',
            onOk: () => {
              orderFeeDel({ id: record.id }).then(() => {
                Notification.success({
                  content: '删除成功',
                  closable: true,
                  duration: 3000,
                })
                loadCompulsoryData()
              })
            },
          })
        },
      },
    ],
  })

  const selectionChange = (e: number[]) => {
    expensesKeys.value = e
  }

  // 批量结算
  const batchExpensesFn = () => {
    if (expensesKeys.value.length == 0) {
      Message.warning('请选择费用项')
      return false
    }
    // 判断是否包含可以结算的费项
    const tableList = cloneTableCompulsory.value
    // 判断是否包含可以结算的费项
    const filterCanConfirmKeys = expensesKeys.value.filter((feeId) => {
      const record = tableList.find((item) => item.id == feeId)
      const disabled =
        (record.feeType == 2 && ![1000, -100].includes(shortOrderDetails?.value?.orderStatus)) || [2, 9].includes(record.feeStatus)
      return !disabled
    })
    if (filterCanConfirmKeys.length == 0) {
      Message.warning('您选择的费项都为已结算，无可结算金额')
      expensesKeys.value = []
    } else {
      checkManyToConfirm({ idList: filterCanConfirmKeys }).then((res: any) => {
        if (res.code == 200) {
          settlementModalRef.value.show(JSON.stringify(filterCanConfirmKeys), { orderId: props.orderId })
        } else {
          Message.warning(res.message)
          return false
        }
      })
    }
  }

  const qcodeConfirm = (details: any) => {
    qcodeCfLoading.value = true

    cancelPay({ id: details.id })
      .then(() => {
        Message.success('取消收款成功')
        payQCodeModal.value = false
        getFeeAmount()
      })
      .finally(() => {
        qcodeCfLoading.value = false
      })
  }

  const payQCodeClose = () => {
    tableCompulsory.tableLoading = true
    setTimeout(() => {
      console.log('3s close')
      loadCompulsoryData()
    }, 3000)
  }

  // 确认成功
  const feepageConfirm = () => {
    console.log('确认成功')
    expensesKeys.value = []
    loadCompulsoryData()
    getFeeAmount()
  }

  // 功能及名词解释
  const funsAndNounVisible = ref(false)
  const viewSettlementModalVisible = ref(false)
  const viewSettlementModalData = ref({})
  // 查看结算明细
  const settlementViewFn = () => {
    viewSettlementModalData.value = {
      id: props.orderId,
    }
    viewSettlementModalVisible.value = true
  }
  // 批量撤销结算
  const batchRevokeConfirmFeeFn = () => {
    // 如选择的费项中有不支持驳回的费项，点击批量驳回时，
    // 仅展示支持驳回的费项信息，如都不符合，则点击批量驳回时，提示商户：无可驳回的费项，请重新选择
    if (expensesKeys.value.length) {
      const tableList = cloneTableCompulsory.value
      // 根据选中的id转换为record列表
      const filteredData = tableList.filter((record: { id: number }) => {
        return expensesKeys.value.includes(record.id)
      })
      // 支持驳回：已结算未对账的金额
      const filteredArray = filteredData.filter((item: any) => item.payAmount !== 0 && item.waitBillAmount !== 0 && item.billStatus != 9 && item.payType != 4)
      if (filteredArray.length) {
        Modal.confirm({
          title: '批量撤销结算',
          content: () =>
            h('div', {}, [
              h('p', {}, `您选择了${expensesKeys.value.length}笔费项，其中${filteredArray.length}笔费项支持撤销，确认撤销结算吗？`),
              h('p', { style: 'color: red' }, '注：'),
              h('p', { style: 'color: red' }, '1.未对账的金额支持撤销结算，撤销后需重新结算'),
              h('p', { style: 'color: red' }, '2.支付方式为聚合支付的金额不支持撤销结算'),
              h('p', { style: 'color: red' }, '3.支付方式为押金抵扣且使用芝麻免押的不支持撤销结算'),
            ]),
          onOk: () => {
            const idList = filteredArray.map((item: { id: number }) => item.id)
            rejectShortOrderBill({ idList: idList, operateType: 2 }).then((res: any) => {
              Message.success(res.message)
              // 清空选中
              expensesKeys.value = []
              loadCompulsoryData()
            })
          },
        })
      } else {
        Message.warning('无可撤销结算的费项，请重新选择')
        expensesKeys.value = []
      }
    } else {
      Message.warning('请选择费用项')
    }
  }
  // 添加用户缴费弹窗
  const addfeeFn = () => {
    addFeeModalRef.value.show()
  }

  // 获取费用总额
  const amountCount = ref<any>({})
  const getFeeAmount = () => {
    feeAmountCount({ orderId: props.orderId }).then((res: any) => {
      const { result } = res
      amountCount.value = result
    })
  }
  const addFeeOkFn = () => {
    loadCompulsoryData()
    getFeeAmount()
  }
  onMounted(() => {
    getShortOrderDetail().then((res: any) => {
      shortOrderDetails.value = res.orderInfo
      loadCompulsoryData()
      getFeeAmount()
      getFeeItemName()
      getOrderNotice()
    })
  })
</script>

<style lang="less" scoped>
  :deep(.arco-table-expand-btn) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-expand-btn:hover) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-td-content:empty::before) {
    content: ' ';
  }

  .custom-alert {
    :deep(.arco-alert-body) {
      overflow: hidden;
    }
  }

  .w-49 {
    width: 49.5%;
  }

  .bg-f7f8fa {
    background: #f7f8fa;
  }

  .bg-eef0f4 {
    background: #eef0f4;
  }

  .outline-e5e6eb {
    border-color: #e5e6eb;
  }

  .text-191c27 {
    color: #191c27;
  }

  .text-4e5969 {
    color: #4e5969;
  }

  .text-1890ff {
    color: #1890ff;
  }

  .color-1890ff {
    color: #1890ff;
  }
</style>
